<?php

namespace app\admin\controller\food;
use think\Db;
use think\exception\PDOException;
use think\exception\ValidateException;
use think\Exception;
use app\common\controller\Backend;

/**
 * 中国菜品列表主管理
 *
 * @icon fa fa-circle-o
 */
class Dish extends Backend
{

    /**
     * Dish模型对象
     * @var \app\admin\model\food\Dish
     */
    protected $model = null;

    public function _initialize()
    {
        parent::_initialize();
        $this->model = new \app\admin\model\food\Dish;
        $this->view->assign("dishTypeList", $this->model->getDishTypeList());
        $this->view->assign("difficultyList", $this->model->getDifficultyList());
        $this->view->assign("statusList", $this->model->getStatusList());
    }



    /**
     * 编辑
     */
    public function edit($ids = null)
    {
        $row = $this->model->get($ids);
        if (!$row) {
            $this->error(__('No Results were found'));
        }
        $adminIds = $this->getDataLimitAdminIds();
        if (is_array($adminIds) && !in_array($row[$this->dataLimitField], $adminIds)) {
            $this->error(__('You have no permission'));
        }
        if ($this->request->isPost()) {
            $params = $this->request->post("row/a");
            if ($params) {
                $params = $this->preExcludeFields($params);
                $result = false;
                Db::startTrans();
                try {
                    // 更新菜品基本信息
                    if ($this->modelValidate) {
                        $name = str_replace("\\model\\", "\\validate\\", get_class($this->model));
                        $validate = is_bool($this->modelValidate) ? ($this->modelSceneValidate ? $name . '.edit' : $name) : $this->modelValidate;
                        $row->validateFailException(true)->validate($validate);
                    }
                    $result = $row->allowField(true)->save($params);
                    
                    // 更新食材关联
                    $ingredientData = $this->request->post('row.ingredient_data');
                    if (isset($ingredientData)) {
                        // 先删除原有的食材关联
                        Db::table('fa_food_ingredientrel')->where('dish_id', $ids)->delete();
                        
                        // 添加新的食材关联
                        if (!empty($ingredientData)) {
                            $this->saveDishIngredientRelations($ids, $ingredientData);
                        }
                    }
                    
                    Db::commit();
                } catch (ValidateException $e) {
                    Db::rollback();
                    $this->error($e->getMessage());
                } catch (PDOException $e) {
                    Db::rollback();
                    $this->error($e->getMessage());
                } catch (Exception $e) {
                    Db::rollback();
                    $this->error($e->getMessage());
                }
                if ($result !== false) {
                    $this->success();
                } else {
                    $this->error(__('No rows were updated'));
                }
            }
            $this->error(__('Parameter %s can not be empty', ''));
        }
        
        // 获取已选择的食材数据
        $ingredientData = $this->getDishIngredientsData($ids);
        
        $this->view->assign('ingredientData', $ingredientData);
        $this->view->assign('row', $row);
        return $this->view->fetch();
    }
    
    /**
     * 添加
     */
    public function add()
    {
        if ($this->request->isPost()) {
            $params = $this->request->post("row/a");
            if ($params) {
                $params = $this->preExcludeFields($params);

                if ($this->dataLimit && $this->dataLimitFieldAutoFill) {
                    $params[$this->dataLimitField] = $this->auth->id;
                }
                $result = false;
                Db::startTrans();
                try {
                    // 保存菜品基本信息
                    if ($this->modelValidate) {
                        $name = str_replace("\\model\\", "\\validate\\", get_class($this->model));
                        $validate = is_bool($this->modelValidate) ? ($this->modelSceneValidate ? $name . '.add' : $name) : $this->modelValidate;
                        $this->model->validateFailException(true)->validate($validate);
                    }
                    $result = $this->model->allowField(true)->save($params);
                    
                    // 获取新增的菜品ID
                    $dishId = $this->model->id;
                    
                    // 保存食材关联
                    $ingredientData = $this->request->post('row.ingredient_data');
                    if (!empty($ingredientData)) {
                        $this->saveDishIngredientRelations($dishId, $ingredientData);
                    }
                    
                    Db::commit();
                } catch (ValidateException $e) {
                    Db::rollback();
                    $this->error($e->getMessage());
                } catch (PDOException $e) {
                    Db::rollback();
                    $this->error($e->getMessage());
                } catch (Exception $e) {
                    Db::rollback();
                    $this->error($e->getMessage());
                }
                if ($result !== false) {
                    $this->success();
                } else {
                    $this->error(__('No rows were inserted'));
                }
            }
            $this->error(__('Parameter %s can not be empty', ''));
        }
        return $this->view->fetch();
    }

    /**
     * 获取所有分类数据用于对话框选择
     */
    public function getCategories()
    {
        if (!$this->request->isAjax()) {
            $this->error(__('Invalid request'));
        }
        
        $dishId = $this->request->post('dish_id'); // 获取菜品ID
        
        try {
            $result = [];
            
            // 获取人群分类
            $crowdModel = new \app\admin\model\food\Crowd;
            $crowds = $crowdModel->where('status', 1)->field('id,name,parent_id')->order('weigh ASC,id ASC')->select();
            // 确保parent_id是整数类型
            foreach ($crowds as &$item) {
                $item['parent_id'] = intval($item['parent_id']);
            }
            $result['crowd'] = $crowds;
            
            // 获取菜系分类
            $cuisineModel = new \app\admin\model\food\Cuisine;
            $cuisines = $cuisineModel->where('status', 1)->field('id,name,parent_id')->order('weigh ASC,id ASC')->select();
            // 确保parent_id是整数类型
            foreach ($cuisines as &$item) {
                $item['parent_id'] = intval($item['parent_id']);
            }
            $result['cuisine'] = $cuisines;
            
            // 获取食材形态分类
            $formModel = new \app\admin\model\food\Form;
            $forms = $formModel->where('status', 1)->field('id,name,parent_id,type')->order('weigh ASC,id ASC')->select();
            // 确保parent_id是整数类型
            foreach ($forms as &$item) {
                $item['parent_id'] = intval($item['parent_id']);
            }
            $result['form'] = $forms;
            
            // 获取营养分类
            $nutritionModel = new \app\admin\model\food\Nutrition;
            $nutritions = $nutritionModel->where('status', 1)->field('id,name,parent_id,type')->order('weigh ASC,id ASC')->select();
            // 确保parent_id是整数类型
            foreach ($nutritions as &$item) {
                $item['parent_id'] = intval($item['parent_id']);
            }
            $result['nutrition'] = $nutritions;
            
            // 获取时段分类
            $periodModel = new \app\admin\model\food\Period;
            $periods = $periodModel->where('status', 1)->field('id,name,parent_id,time_range')->order('weigh ASC,id ASC')->select();
            // 确保parent_id是整数类型
            foreach ($periods as &$item) {
                $item['parent_id'] = intval($item['parent_id']);
            }
            $result['period'] = $periods;
            
            // 获取场景分类
            $sceneModel = new \app\admin\model\food\Scene;
            $scenes = $sceneModel->where('status', 1)->field('id,name,parent_id,type')->order('weigh ASC,id ASC')->select();
            // 确保parent_id是整数类型
            foreach ($scenes as &$item) {
                $item['parent_id'] = intval($item['parent_id']);
            }
            $result['scene'] = $scenes;
            
            // 获取工艺技术分类
            $techModel = new \app\admin\model\food\Tech;
            $techs = $techModel->where('status', 1)->field('id,name,parent_id,type')->order('weigh ASC,id ASC')->select();
            // 确保parent_id是整数类型
            foreach ($techs as &$item) {
                $item['parent_id'] = intval($item['parent_id']);
            }
            $result['tech'] = $techs;
            
            // 获取地域分类
            $regionModel = new \app\admin\model\food\Region;
            $regions = $regionModel->field('id,name,parent_id')->order('weigh ASC,id ASC')->select();
            // 确保parent_id是整数类型
            foreach ($regions as &$item) {
                $item['parent_id'] = intval($item['parent_id']);
            }
            $result['region'] = $regions;
            
            // 如果提供了菜品ID，获取已选择的分类
            if ($dishId) {
                $result['selected'] = $this->getSelectedCategoriesByDishId($dishId);
            }
            
            return json(['code' => 1, 'msg' => 'success', 'data' => $result]);
            
        } catch (\Exception $e) {
            return json(['code' => 0, 'msg' => $e->getMessage()]);
        }
    }
    
    /**
     * 根据菜品ID获取已选择的分类
     */
    private function getSelectedCategoriesByDishId($dishId)
    {
        $selected = [
            'crowd_ids' => [],
            'cuisine_ids' => [],
            'form_ids' => [],
            'nutrition_ids' => [],
            'period_ids' => [],
            'region_ids' => [],
            'scene_ids' => [],
            'tech_ids' => []
        ];
        
        try {
            // 获取各个关联表的数据
            $relationMaps = [
                'crowd_ids' => ['table' => 'fa_food_crowdrel', 'field' => 'crowd_id'],
                'cuisine_ids' => ['table' => 'fa_food_cuisinerel', 'field' => 'cuisine_id'],
                'form_ids' => ['table' => 'fa_food_formrel', 'field' => 'form_id'],
                'nutrition_ids' => ['table' => 'fa_food_nutritionrel', 'field' => 'nutrition_id'],
                'period_ids' => ['table' => 'fa_food_periodrel', 'field' => 'period_id'],
                'region_ids' => ['table' => 'fa_food_regionrel', 'field' => 'region_id'],
                'scene_ids' => ['table' => 'fa_food_scenerel', 'field' => 'scene_id'],
                'tech_ids' => ['table' => 'fa_food_techrel', 'field' => 'tech_id']
            ];
            
            foreach ($relationMaps as $key => $config) {
                $records = Db::table($config['table'])
                    ->where('dish_id', $dishId)
                    ->column($config['field']);
                $selected[$key] = array_map('intval', $records); // 转换为整数数组
            }
            
        } catch (\Exception $e) {
            \think\Log::error('getSelectedCategoriesByDishId error: ' . $e->getMessage());
        }
        
        return $selected;
    }
    
    /**
     * 保存菜品分类关联数据
     */
    public function saveCategories()
    {
        if (!$this->request->isAjax()) {
            $this->error(__('Invalid request'));
        }
        
        $dishId = $this->request->post('dish_id');
        $categoriesJson = $this->request->post('categories');
        
        // 调试信息
        \think\Log::info('saveCategories - dishId: ' . $dishId);
        \think\Log::info('saveCategories - categoriesJson: ' . var_export($categoriesJson, true));
        
        if (!$dishId) {
            return json(['code' => 0, 'msg' => '菜品ID不能为空']);
        }
        
        if (!$categoriesJson) {
            return json(['code' => 0, 'msg' => '分类数据不能为空']);
        }
        
        // 如果categories是JSON字符串，需要解码
        if (is_string($categoriesJson)) {
            $categories = json_decode($categoriesJson, true);
            if (json_last_error() !== JSON_ERROR_NONE) {
                return json(['code' => 0, 'msg' => 'JSON解码失败：' . json_last_error_msg()]);
            }
        } else {
            $categories = $categoriesJson;
        }
        
        if (!$categories || !is_array($categories)) {
            return json(['code' => 0, 'msg' => '分类数据格式错误']);
        }
        
        \think\Log::info('saveCategories - parsed categories: ' . var_export($categories, true));
        
        Db::startTrans();
        try {
            // 先删除该菜品的所有分类关联
            $this->deleteAllDishCategories($dishId);
            
            // 保存新的关联数据
            $this->saveDishCategoryRelations($dishId, $categories);
            
            Db::commit();
            return json(['code' => 1, 'msg' => '保存成功']);
            
        } catch (\Exception $e) {
            Db::rollback();
            \think\Log::error('saveCategories error: ' . $e->getMessage());
            return json(['code' => 0, 'msg' => '保存失败：' . $e->getMessage()]);
        }
    }
    
    /**
     * 获取食材数据用于选择
     */
    public function getIngredients()
    {
        if (!$this->request->isAjax()) {
            $this->error(__('Invalid request'));
        }
        
        try {
            // 获取食材分类，添加拼音支持
            $categoriesModel = new \app\admin\model\food\Categories;
            $categories = $categoriesModel->where('status', 'normal')
                ->field('id,name,parent_id')
                ->order('weigh ASC,id ASC')
                ->select();
            
            // 为分类添加拼音简写支持，并确保 parent_id 是整数
            foreach ($categories as &$category) {
                $category['pinyin'] = $this->getPinyin($category['name']);
                $category['parent_id'] = intval($category['parent_id']); // 确保是整数类型
            }
            
            $result = [
                'categories' => $categories
            ];
            
            return json(['code' => 1, 'msg' => '获取成功', 'data' => $result]);
            
        } catch (\Exception $e) {
            \think\Log::error('getIngredients error: ' . $e->getMessage());
            return json(['code' => 0, 'msg' => '获取失败：' . $e->getMessage()]);
        }
    }
    
    /**
     * 根据分类获取食材列表
     */
    public function getIngredientsByCategory()
    {
        if (!$this->request->isAjax()) {
            $this->error(__('Invalid request'));
        }
        
        $categoryId = $this->request->post('category_id');
        
        if (empty($categoryId)) {
            return json(['code' => 0, 'msg' => '分类ID不能为空']);
        }
        
        try {
            // 获取该分类下的食材，添加拼音支持
            $ingredientModel = new \app\admin\model\food\Ingredient;
            $ingredients = $ingredientModel->where('categories_id', $categoryId)
                ->where('status', 'normal')
                ->field('id,name,weight,energy_kilocalorie')
                ->order('weigh ASC,id ASC')
                ->select();
            
            // 为食材添加拼音简写支持
            foreach ($ingredients as &$ingredient) {
                $ingredient['pinyin'] = $this->getPinyin($ingredient['name']);
            }
            
            $result = [
                'ingredients' => $ingredients
            ];
            
            return json(['code' => 1, 'msg' => '获取成功', 'data' => $result]);
            
        } catch (\Exception $e) {
            \think\Log::error('getIngredientsByCategory error: ' . $e->getMessage());
            return json(['code' => 0, 'msg' => '获取失败：' . $e->getMessage()]);
        }
    }
    
    /**
     * 根据一级分类获取所有子分类的食材列表
     */
    public function getIngredientsByParentCategory()
    {
        if (!$this->request->isAjax()) {
            $this->error(__('Invalid request'));
        }
        
        $parentCategoryId = $this->request->post('parent_category_id');
        
        if (empty($parentCategoryId)) {
            return json(['code' => 0, 'msg' => '一级分类ID不能为空']);
        }
        
        try {
            // 首先获取该一级分类下的所有子分类
            $categoriesModel = new \app\admin\model\food\Categories;
            $childCategories = $categoriesModel->where('parent_id', $parentCategoryId)
                ->where('status', 'normal')
                ->field('id,name')
                ->order('weigh ASC,id ASC')
                ->select();
            
            if (empty($childCategories)) {
                return json(['code' => 1, 'msg' => '该分类下暂无子分类', 'data' => ['ingredients' => []]]);
            }
            
            // 提取子分类ID
            $childCategoryIds = [];
            $categoryNameMap = [];
            foreach ($childCategories as $category) {
                $childCategoryIds[] = $category['id'];
                $categoryNameMap[$category['id']] = $category['name'];
            }
            
            // 获取所有子分类下的食材
            $ingredientModel = new \app\admin\model\food\Ingredient;
            $ingredients = $ingredientModel->where('categories_id', 'in', $childCategoryIds)
                ->where('status', 'normal')
                ->field('id,name,weight,energy_kilocalorie,categories_id')
                ->order('categories_id ASC,weigh ASC,id ASC')
                ->select();
            
            // 为食材添加分类名称和拼音支持
            $result = [];
            foreach ($ingredients as $ingredient) {
                $categoryId = $ingredient['categories_id'];
                $ingredient['category_id'] = $categoryId;
                $ingredient['category_name'] = $categoryNameMap[$categoryId] ?? '未知分类';
                $ingredient['pinyin'] = $this->getPinyin($ingredient['name']);
                $result[] = $ingredient;
            }
            
            return json([
                'code' => 1, 
                'msg' => '获取成功', 
                'data' => [
                    'ingredients' => $result,
                    'parent_category_id' => $parentCategoryId,
                    'child_categories_count' => count($childCategories)
                ]
            ]);
            
        } catch (\Exception $e) {
            \think\Log::error('getIngredientsByParentCategory error: ' . $e->getMessage());
            return json(['code' => 0, 'msg' => '获取失败：' . $e->getMessage()]);
        }
    }
    
    /**
     * 获取菜品的食材数据
     */
    private function getDishIngredientsData($dishId)
    {
        try {
            \think\Log::info('getDishIngredientsData - dishId: ' . $dishId);
            
            // 先检查关联表数据
            $relationCount = Db::table('fa_food_ingredientrel')
                ->where('dish_id', $dishId)
                ->count();
            \think\Log::info('getDishIngredientsData - relation count: ' . $relationCount);
            
            if ($relationCount == 0) {
                \think\Log::info('getDishIngredientsData - no relations found');
                return '';
            }
            
            // 获取关联数据（不包含 JOIN）
            $relations = Db::table('fa_food_ingredientrel')
                ->where('dish_id', $dishId)
                ->field('ingredient_id, quantity')
                ->order('weigh ASC')
                ->select();
            
            \think\Log::info('getDishIngredientsData - basic relations: ' . json_encode($relations));
            
            // 获取食材的详细信息
            $ingredientData = [];
            foreach ($relations as $relation) {
                $ingredientInfo = Db::table('fa_food_ingredient')
                    ->where('id', $relation['ingredient_id'])
                    ->field('id, name, energy_kilocalorie')
                    ->find();
                
                \think\Log::info('getDishIngredientsData - ingredient ' . $relation['ingredient_id'] . ': ' . json_encode($ingredientInfo));
                
                if ($ingredientInfo) {
                    // 解析重量字符串，去掉单位
                    $quantityStr = $relation['quantity'] ?? '100g';
                    $quantity = floatval(str_replace(['g', 'G', '克'], '', $quantityStr));
                    if ($quantity <= 0) {
                        $quantity = 100; // 默认值
                    }
                    
                    $ingredientData[] = [
                        'id' => intval($ingredientInfo['id']),
                        'name' => $ingredientInfo['name'] ?? '',
                        'quantity' => $quantity,
                        'unitEnergy' => floatval($ingredientInfo['energy_kilocalorie'] ?? 0)
                    ];
                } else {
                    \think\Log::warning('getDishIngredientsData - ingredient not found: ' . $relation['ingredient_id']);
                }
            }
            
            $jsonData = json_encode($ingredientData, JSON_UNESCAPED_UNICODE | JSON_UNESCAPED_SLASHES);
            \think\Log::info('getDishIngredientsData - final JSON: ' . $jsonData);
            
            return $jsonData;
            
        } catch (\Exception $e) {
            \think\Log::error('getDishIngredientsData error: ' . $e->getMessage());
            \think\Log::error('getDishIngredientsData stack trace: ' . $e->getTraceAsString());
            return '';
        }
    }
    

    /**
     * 获取拼音简写
     * 这是一个简单的拼音处理方法，实际中可以使用更完善的拼音库
     */
    private function getPinyin($chinese)
    {
        // 这里可以集成拼音库，暂时返回空字符串
        // 建议在数据库中直接存储拼音字段
        return '';
    }
    
    /**
     * 删除菜品的所有分类关联
     */
    private function deleteAllDishCategories($dishId)
    {
        $tables = [
            'fa_food_crowdrel',
            'fa_food_cuisinerel', 
            'fa_food_formrel',
            'fa_food_nutritionrel',
            'fa_food_periodrel',
            'fa_food_regionrel',
            'fa_food_scenerel',
            'fa_food_techrel'
        ];
        
        foreach ($tables as $table) {
            Db::table($table)->where('dish_id', $dishId)->delete();
        }
    }
    
    /**
     * 保存菜品分类关联数据
     */
    private function saveDishCategoryRelations($dishId, $categories)
    {
        $relationMaps = [
            'crowd_ids' => ['table' => 'fa_food_crowdrel', 'field' => 'crowd_id'],
            'cuisine_ids' => ['table' => 'fa_food_cuisinerel', 'field' => 'cuisine_id'],
            'form_ids' => ['table' => 'fa_food_formrel', 'field' => 'form_id'], 
            'nutrition_ids' => ['table' => 'fa_food_nutritionrel', 'field' => 'nutrition_id'],
            'period_ids' => ['table' => 'fa_food_periodrel', 'field' => 'period_id'],
            'region_ids' => ['table' => 'fa_food_regionrel', 'field' => 'region_id'],
            'scene_ids' => ['table' => 'fa_food_scenerel', 'field' => 'scene_id'],
            'tech_ids' => ['table' => 'fa_food_techrel', 'field' => 'tech_id']
        ];
        
        foreach ($relationMaps as $categoryKey => $config) {
            if (isset($categories[$categoryKey]) && is_array($categories[$categoryKey])) {
                $insertData = [];
                foreach ($categories[$categoryKey] as $categoryId) {
                    $insertData[] = [
                        'dish_id' => $dishId,
                        $config['field'] => $categoryId,
                        'createtime' => time()
                    ];
                }
                
                if (!empty($insertData)) {
                    try {
                        Db::table($config['table'])->insertAll($insertData);
                        \think\Log::info('Successfully inserted ' . count($insertData) . ' records to ' . $config['table']);
                    } catch (\Exception $e) {
                        \think\Log::error('Insert failed for table ' . $config['table'] . ': ' . $e->getMessage());
                        throw $e;
                    }
                }
            }
        }
    }
    
    /**
     * 保存菜品食材关联数据
     */
    private function saveDishIngredientRelations($dishId, $ingredientData)
    {
        if (empty($ingredientData)) {
            return;
        }
        
        try {
            // 解析JSON数据
            $data = json_decode($ingredientData, true);
            if (!is_array($data)) {
                throw new \Exception('食材数据格式错误');
            }
            
            $insertData = [];
            foreach ($data as $index => $ingredient) {
                if (isset($ingredient['id']) && $ingredient['id'] > 0) {
                    $insertData[] = [
                        'dish_id' => $dishId,
                        'ingredient_id' => intval($ingredient['id']),
                        'quantity' => floatval($ingredient['quantity'] ?? 100) . 'g', // 保存为字符串格式
                        'createtime' => time(),
                        'weigh' => $index + 1
                    ];
                }
            }
            
            if (!empty($insertData)) {
                Db::table('fa_food_ingredientrel')->insertAll($insertData);
                \think\Log::info('Successfully inserted ' . count($insertData) . ' ingredient relations with quantities');
            }
            
        } catch (\Exception $e) {
            \think\Log::error('Insert ingredient relations failed: ' . $e->getMessage());
            throw $e;
        }
    }


    /**
     * 查看
     */
    public function index()
    {
        //当前是否为关联查询
        $this->relationSearch = false;
        //设置过滤方法
        $this->request->filter(['strip_tags', 'trim']);
        if ($this->request->isAjax()) {
            //如果发送的来源是Selectpage，则转发到Selectpage
            if ($this->request->request('keyField')) {
                return $this->selectpage();
            }
            list($where, $sort, $order, $offset, $limit) = $this->buildparams();

            $list = $this->model
                    ->with(['ingredientrels'])
                    ->where($where)
                    ->order($sort, $order)
                    ->paginate($limit);

            foreach ($list as $row) {
                $row->visible(['id','name','dish_type','image','cook_time','difficulty','createtime','status','weigh']);
                
                // 检查是否有ingredient_id为0的关联记录
                $hasZeroIngredient = false;
                if ($row->ingredientrels) {
                    foreach ($row->ingredientrels as $rel) {
                        if (isset($rel['ingredient_id']) && $rel['ingredient_id'] == 0) {
                            $hasZeroIngredient = true;
                            break;
                        }
                    }
                }
                
                // 添加一个字段标识是否有ingredient_id为0的记录
                $row->setAttr('has_zero_ingredient', $hasZeroIngredient ? 1 : 0);
                $row->visible(['has_zero_ingredient']);
            }

            $result = array("total" => $list->total(), "rows" => $list->items());

            return json($result);
        }
        return $this->view->fetch();
    }
    
    /**
     * 根据一级分类获取所有子分类的食材列表（简短版）
     */
    public function getIngredientsByParent()
    {
        return $this->getIngredientsByParentCategory();
    }
    
    /**
     * 通过阿里云千问API获取菜品制作信息
     */
    public function getDishInfoFromQwen()
    {
        if (!$this->request->isAjax()) {
            $this->error(__('Invalid request'));
        }
        
        $dishId = $this->request->post('dish_id');
        if (empty($dishId)) {
            return json(['code' => 0, 'msg' => '菜品ID不能为空']);
        }
        
        // 获取菜品信息
        $dish = $this->model->get($dishId);
        if (!$dish) {
            return json(['code' => 0, 'msg' => '菜品不存在']);
        }
        
        $dishName = $dish['name'];
        if (empty($dishName)) {
            return json(['code' => 0, 'msg' => '菜品名称不能为空']);
        }
        
        // 阿里云千问API配置
        $apiKey = 'sk-416b931b781c420c9f6331b7346962b5';
        $apiUrl = 'https://dashscope.aliyuncs.com/api/v1/services/aigc/text-generation/generation';
        $model = 'qwen-doc-turbo';
        
        // 构造请求内容
        $prompt = "菜品名称：{$dishName} 请根据提供的食材JSON数据，列出上面所需食材及食材所需克重配比。请严格按照JSON中的食材名称进行匹配并获取对应的ID。格式如：鸡蛋：150 西红柿：300 食用油：20 盐：3 白糖：5 葱花：5 水不用列出 请列出烹饪时长，以分钟为节点 如：时长：7 制作步骤： 1、热锅凉油，倒入蛋液，中火煎至底部凝固后翻炒成块，盛出备用 2、锅中补少许油，爆香蒜末/葱白，下西红柿翻炒至出汁 3、加入炒好的鸡蛋，加盐、糖调味，翻炒均匀，可加少量水略焖 4、撒葱花，淋少许生抽（可选），翻炒出锅";
       
        $data = [
            'model' => $model,
            'input' => [
                'messages' => [
                    [
                        'role' => 'system',
                        'content' => 'you are a helpful assistant.'
                    ],
                    [
                        'role' => 'user',
                        'content' => [
                            [
                                'type' => 'text',
                                'text' => $prompt
                            ],
                            [
                                'type' => 'doc_url',
                                'doc_url' => [
                                    'https://fengou-bcahz.oss-cn-beijing.aliyuncs.com/fa_food_ingredient.json?Expires=1758196908&OSSAccessKeyId=TMP.3KsWLQ7GzDbcef9FYVaZFoFp37d1NppprgAqy4q3xDZ33J4zuiMq6GPoiDHgrGpkkg7Vgog1Zi6mdQzF4N1J8TEnbwPzfT&Signature=n1ESyiTh5oNUSNAxrTXK3%2Bw9IZg%3D'
                                ],
                                'file_parsing_strategy' => 'auto'
                            ]
                        ]
                    ]
                ]
            ],
            'parameters' => [
                'enable_search' => false,
                'incremental_output' => false,
                'result_format' => 'message'
            ]
        ];
         
        // 发送请求到阿里云千问API
        $headers = [
            'Content-Type: application/json',
            'Authorization: Bearer ' . $apiKey,
            'Accept: application/json'
        ];
        
        $ch = curl_init();
        curl_setopt($ch, CURLOPT_URL, $apiUrl);
        curl_setopt($ch, CURLOPT_POST, true);
        curl_setopt($ch, CURLOPT_POSTFIELDS, json_encode($data, JSON_UNESCAPED_UNICODE));
        curl_setopt($ch, CURLOPT_HTTPHEADER, $headers);
        curl_setopt($ch, CURLOPT_RETURNTRANSFER, true);
        curl_setopt($ch, CURLOPT_SSL_VERIFYPEER, false);
        curl_setopt($ch, CURLOPT_TIMEOUT, 60); // 增加超时时间到60秒
        curl_setopt($ch, CURLOPT_CONNECTTIMEOUT, 30); // 连接超时30秒
        curl_setopt($ch, CURLOPT_FOLLOWLOCATION, true); // 跟随重定向
        curl_setopt($ch, CURLOPT_MAXREDIRS, 3); // 最大重定向次数
        curl_setopt($ch, CURLOPT_USERAGENT, 'FastAdmin Dish AI Generator'); // 设置用户代理
        
        $response = curl_exec($ch);
        $httpCode = curl_getinfo($ch, CURLINFO_HTTP_CODE);
        $error = curl_error($ch);
        curl_close($ch);
        // halt([$apiKey, $apiUrl, $model, $prompt, $data, $headers, $response]);
        if ($error) {
            \think\Log::error('Qwen API request error: ' . $error);
            return json(['code' => 0, 'msg' => '调用AI接口失败：' . $error]);
        }
        
        if ($httpCode !== 200) {
            \think\Log::error('Qwen API response error. HTTP Code: ' . $httpCode . ', Response: ' . $response);
            return json(['code' => 0, 'msg' => 'AI接口返回错误，HTTP状态码：' . $httpCode]);
        }
        
        $result = json_decode($response, true);
        if (json_last_error() !== JSON_ERROR_NONE) {
            \think\Log::error('Qwen API response JSON decode error: ' . json_last_error_msg());
            return json(['code' => 0, 'msg' => 'AI接口返回数据解析失败']);
        }
        
        // 解析API返回结果
        $content = $result['output']['choices'][0]['message']['content'] ?? '';
        if (empty($content)) {
            return json(['code' => 0, 'msg' => 'AI接口返回内容为空']);
        }
        
        // 从API返回内容中提取食材信息和ID
        $ingredientsJsonUrl = 'https://fengou-bcahz.oss-cn-beijing.aliyuncs.com/fa_food_ingredient.json?Expires=1758196908&OSSAccessKeyId=TMP.3KsWLQ7GzDbcef9FYVaZFoFp37d1NppprgAqy4q3xDZ33J4zuiMq6GPoiDHgrGpkkg7Vgog1Zi6mdQzF4N1J8TEnbwPzfT&Signature=n1ESyiTh5oNUSNAxrTXK3%2Bw9IZg%3D';
        $ingredientsJson = @file_get_contents($ingredientsJsonUrl);
        if ($ingredientsJson === false) {
            return json(['code' => 0, 'msg' => '获取食材数据失败']);
        }
        
        $availableIngredients = json_decode($ingredientsJson, true);
        if (json_last_error() !== JSON_ERROR_NONE) {
            return json(['code' => 0, 'msg' => '食材数据JSON解析失败']);
        }
        
        // 解析AI返回的内容，提取制作步骤、烹饪时长和食材信息
        $parsedInfo = $this->parseQwenResponse($content, $availableIngredients);
        if (!$parsedInfo) {
            return json(['code' => 0, 'msg' => '解析AI返回内容失败']);
        }
        
        Db::startTrans();
        try {
            // 更新菜品的制作步骤和烹饪时长
            $updateData = [
                'steps' => $parsedInfo['steps'],
                'cook_time' => $parsedInfo['cook_time']
            ];
            
            $this->model->where('id', $dishId)->update($updateData);
            
            // 删除原有的食材关联
            Db::table('fa_food_ingredientrel')->where('dish_id', $dishId)->delete();
            
            // 添加新的食材关联
            if (!empty($parsedInfo['ingredients'])) {
                $this->saveDishIngredientRelations($dishId, json_encode($parsedInfo['ingredients']));
            }
            
            Db::commit();
            return json(['code' => 1, 'msg' => '更新成功', 'data' => $parsedInfo]);
            
        } catch (\Exception $e) {
            Db::rollback();
            \think\Log::error('Update dish info error: ' . $e->getMessage());
            return json(['code' => 0, 'msg' => '更新失败：' . $e->getMessage()]);
        }
    }
    
    /**
     * 解析阿里云千问API返回的内容
     */
    private function parseQwenResponse($content, $availableIngredients)
    {
        $result = [
            'steps' => '',
            'cook_time' => '',
            'ingredients' => []
        ];
        
        // 提取烹饪时长
        if (preg_match('/时长[：:]\s*(\d+)/', $content, $cookTimeMatches)) {
            $result['cook_time'] = $cookTimeMatches[1] . '分钟';
        }
        
        // 提取制作步骤
        if (preg_match('/制作步骤[：:]\s*([\s\S]*?)(?=\n\n|$)/', $content, $stepsMatches)) {
            $steps = trim($stepsMatches[1]);
            // 清理步骤中的多余空行
            $steps = preg_replace('/\n\s*\n/', "\n", $steps);
            $result['steps'] = $steps;
        }
        
        // 提取食材信息
        $ingredientLines = explode("\n", $content);
        $ingredientData = [];
        
        foreach ($ingredientLines as $line) {
            // 匹配食材名称和重量，如：鸡蛋：150
            if (preg_match('/^([\x{4e00}-\x{9fa5}a-zA-Z]+)[：:]\s*(\d+)/u', $line, $matches)) {
                $ingredientName = $matches[1];
                $weight = intval($matches[2]);
                
                // 在可用食材中查找匹配的食材
                $ingredientId = $this->findIngredientId($ingredientName, $availableIngredients);
                if ($ingredientId) {
                    // 获取食材的单位能量
                    $unitEnergy = 0;
                    foreach ($availableIngredients as $ingredient) {
                        if (isset($ingredient['id']) && $ingredient['id'] == $ingredientId) {
                            $unitEnergy = $ingredient['energy_kilocalorie'] ?? 0;
                            break;
                        }
                    }
                    
                    $ingredientData[] = [
                        'id' => $ingredientId,
                        'name' => $ingredientName,
                        'quantity' => $weight,
                        'unitEnergy' => $unitEnergy
                    ];
                }
            }
        }
        
        $result['ingredients'] = $ingredientData;
        return $result;
    }
    
    /**
     * 在可用食材中查找匹配的食材ID
     */
    private function findIngredientId($ingredientName, $availableIngredients)
    {
        foreach ($availableIngredients as $ingredient) {
            // 直接匹配
            if (isset($ingredient['name']) && $ingredient['name'] === $ingredientName) {
                return $ingredient['id'];
            }
            
            // 模糊匹配（包含关系）
            if (isset($ingredient['name']) && (strpos($ingredient['name'], $ingredientName) !== false || strpos($ingredientName, $ingredient['name']) !== false)) {
                return $ingredient['id'];
            }
        }
        
        return null;
    }

    public function conditions(){
        $id = $this->request->param('id');
        halt($id);
    }

}